package com.example.nettywebsocketdemo.invoke;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: ZhaoJie
 * @Date: 2022/3/28
 * @Description : 通过类的路径以及函数的方法名进行反射调用
 * @Modify :
 * ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
public class InvokeTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        String className = "com.example.nettywebsocketdemo.invoke.FunClass";
        String methodName = "sayHello";
        // 根据名字拿到类并且建立一个新的实例
        Class classProxy = Class.forName(className);
        Object classObject = classProxy.newInstance();
        // 获取方法
        Method method = classObject.getClass().getDeclaredMethod(methodName, String.class);
        //调用方法
        String result = (String) method.invoke(classObject, "aaaaaa");
        System.out.println(result);
    }

}

/**
 * @Author: ZhaoJie
 * @Date: 2022/3/28
 * @Description :
 * @Modify :
 * ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
class FunClass {
    public String sayHello(String s) {
        System.out.println(s);
        return "hello!";
    }
}
